package com.esun.common.utils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author ：Ocean
 * @date ：Created in 2022/1/11 16:17
 * @description：文件工具类
 * @modified By：
 */
public class FileUtils {

    public static boolean checkFileExists(String filePath) {
        return checkFileExists(new File(filePath));
    }

    /**
     * 检查文件是否存在
     *
     * @param file
     * @return
     */
    public static boolean checkFileExists(File file) {
        if (file.exists() && file.isFile() && file.canRead()) {
            return true;
        }
        return false;
    }

    /**
     * 上传文件到服务器（随即生成文件名）
     *
     * @param attachment 附件
     * @param saveDir    //根据业务不同区分不同saveDir
     * @return
     */
    public static String uploadFileToServer(CommonsMultipartFile attachment, String fileName, String saveDir) throws Exception {
        String filePath = null;// 存储路径 包括文件名
        if (attachment != null) {
            saveDir = saveDir.replaceAll("//", "/");

            filePath = saveDir + File.separator + createNewFileName(fileName);
//            String realPath = ConfigUtils.curFileUploadPath() + filePath;
            if (!saveFile2Disk(attachment, getTomcatPath() + filePath)) {
                return null;
            }

        }
        return filePath;
    }

    //根据生成随机文件名 10位随机数+时间毫秒数+后缀名
    public static String createNewFileName(String fileName) {
        Date date = new Date();
        String suffix = FilenameUtils.getExtension(fileName);
        suffix = StringUtils.isBlank(suffix) ? "" : ("." + suffix);
        return UUID.randomUUID().toString() + date.getTime() + suffix;
    }

    //获取tomcat的上传路径
    public static String getTomcatPath() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tomcatWebAppRealPath = request.getSession().getServletContext().getRealPath("/");
        File destDir = new File(tomcatWebAppRealPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return tomcatWebAppRealPath;
    }

    //文件流下载
    public static void downloadFile(HttpServletResponse response, String downFileName, String localFilePath) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM.toString());
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(downFileName.getBytes("UTF-8"), "iso-8859-1"));
        IOUtils.copy(new FileInputStream(localFilePath), response.getOutputStream());
    }

    //保存文件当本地
    public static boolean saveFile2Disk(CommonsMultipartFile attachment, String filePath) throws IOException {
        File targetFile = new File(filePath);
        if (!targetFile.exists() && targetFile.getParentFile() != null) {
            targetFile.getParentFile().mkdirs();
        }
        if (attachment.getFileItem().getSize() == 0) {
            if (targetFile.exists() && targetFile.isFile()) {
                targetFile.delete();
            }
            targetFile.createNewFile();
            return true;
        }

        attachment.transferTo(targetFile);
        return true;
    }

}